package com.zhilianbao.leyaogo.ui.fragment.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.recyclerview.swipe.SwipeMenuItem;
import com.bql.recyclerview.swipe.SwipeMenuRecyclerView;
import com.bql.roundview.RoundTextView;
import com.bql.statetypelayout.AnimationStateTypeLayout;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.SearchApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.category.GoodsInfo;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.shoppingcart.ShoppingCartActivity;
import com.zhilianbao.leyaogo.ui.adapter.home.SearchHistoryAdapter;
import com.zhilianbao.leyaogo.ui.adapter.search.SearchAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseSearchFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.KeyboardUtils;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.layoutmanager.FullyLinearLayoutManager;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;
import com.zhilianbao.leyaogo.view.widgets.TagGroup;
import com.zhilianbao.okhttputils.request.BaseRequest;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ClassName: SearchFragment <br>
 * Description: 搜索Fragment<br>
 * Author: Cyarie <br>
 * Created: 2016/10/25 19:20 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class SearchFragment extends BaseSearchFragment<GoodsInfo> implements OnAddToCartClickListener<GoodsInfo> {

    @BindView(R.id.stateLayout)
    AnimationStateTypeLayout mStateTypeLayout;
    @BindView(R.id.tg_hot_search)
    TagGroup mTgHotSearch;
    @BindView(R.id.ll_search_history)
    LinearLayout mLlSearchHistory;
    @BindView(R.id.ll_search_hot)
    LinearLayout mLlSearchHot;
    @BindView(R.id.sv_search)
    ScrollView mSvSearch;
    @BindView(R.id.iv_add_to_cart)
    ImageView mIvAddToCart;
    @BindView(R.id.iv_clear_history)
    ImageView mIvClearHistory;
    @BindView(R.id.rcv_history)
    SwipeMenuRecyclerView mHistoryRcv;
    @BindView(R.id.iv_cart_num)
    RoundTextView mIvCartNum;
    @BindView(R.id.rl_add_to_cart)
    RelativeLayout mRlAddToCart;
    @BindView(R.id.rl_content)
    MyRelativeLayout mRlContent;

    private SearchAdapter mSearchAdapter;

    private List<String> hotList;

    private List<String> historyList;

    private SearchHistoryAdapter mSearchHistoryAdapter;

    //    private FloatingViewHelper mFloatingViewHelper;

    private String key;

    public static SearchFragment getInstance(List<String> hotList) {
        SearchFragment searchFragment = new SearchFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(IntentConfig.HOT_SEARCH_LIST, (Serializable) hotList);
        searchFragment.setArguments(bundle);
        return searchFragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        Utils.startGoodsDetails(mActivity, mList.get(position).getGoodsId(), mList.get(position).getGoodsSkuId(), false);
    }

    @Override
    public QuickRcvAdapter<GoodsInfo> getAdapter() {
        return mSearchAdapter;
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        if (key != null)
            SearchApi.search(mActivity, key, curPage, pageSize, new RefreshAndLoadCallback<List<GoodsInfo>>(false) {

                @Override
                public void onBefore(BaseRequest request) {
                    super.onBefore(request);
                    mStateTypeLayout.setVisibility(View.VISIBLE);
                }

                @Override
                public void errorLeftOrEmptyBtnClick(View v) {
                    loadDataList(1, false);
                }

                @Override
                public String emptyContent() {
                    return getString(R.string.search_empty_content);
                }

                @Override
                public void onResultSuccess(List<GoodsInfo> o, @Nullable Response response, LoadingViewCallback callback) {
                    mSvSearch.setVisibility(View.GONE);
                    handleRefreshAndLoadListData(curPage, callback, o);
                    if (curPage == 1 && o.size() == 0) {
                        mRlAddToCart.setVisibility(View.GONE);
                    } else if (curPage == 1 && o.size() != 0) {
                        mRlAddToCart.setVisibility(View.VISIBLE);
                    }

                }
            });
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        //        mFloatingViewHelper = new FloatingViewHelper(mActivity);
        hotList = (List<String>) getArguments().getSerializable(IntentConfig.HOT_SEARCH_LIST);
        if (hotList == null)
            hotList = new ArrayList<>();
        historyList = new ArrayList<>();
        mSearchAdapter = new SearchAdapter(mActivity, mList);
        mSearchAdapter.setOnAddCartClickListener(this);
        if (!CheckUtils.isEmpty(hotList)) {
            mLlSearchHot.setVisibility(View.VISIBLE);
            mTgHotSearch.setTags(hotList);
            mEditText.setHint(hotList.get(0));
        } else {
            mLlSearchHot.setVisibility(View.GONE);
        }
        mTgHotSearch.setOnTagClickListener((position, text) -> search(text));
        mStateTypeLayout.setVisibility(View.GONE);
        mRlAddToCart.setVisibility(View.GONE);
        initSearchHistoryRcv();
        initSearchHistory();
        mEditText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                mEditText.setCursorVisible(true);
            } else {
                mEditText.setCursorVisible(false);
            }
        });
        mEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (CheckUtils.isEmpty(mEditText.getText().toString().trim()) && !CheckUtils.isEmpty(hotList)) {
                    search(hotList.get(0));
                } else if (CheckUtils.isEmpty(mEditText.getText().toString().trim()) && CheckUtils.isEmpty(hotList)) {
                    XToastUtils.showShortToast(getString(R.string.please_input_search));
                } else {
                    search(mEditText.getText().toString().trim());
                }
                //                search(mEditText.getText().toString().trim());
            }
            return true;
        });
        ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
        mEditText.addTextChangedListener(contentTextWatcher);
        ThreadPool.postOnUiDelayed(() -> KeyboardUtils.showKeyboard(mActivity, mEditText), 200);
    }

    private TextWatcher contentTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 0) {
                mSvSearch.setVisibility(View.VISIBLE);
                mStateTypeLayout.setVisibility(View.GONE);
                mRlAddToCart.setVisibility(View.GONE);
            }
        }
    };


    /**
     * 进行搜索
     *
     * @param key 关键字
     */
    private void search(String key) {
        this.key = key;
        mEditText.setText(key);
        saveSearchHistory(key);
        KeyboardUtils.hideKeyboard(mActivity);
        mEditText.clearFocus();
        loadDataList(1, false);

        //        AsyncTaskUtils.exe(new AsyncTask<Void, Integer, List<HomeTopic>>() {
        //            @Override
        //            protected void onPreExecute() {
        //                super.onPreExecute();
        //                mStateTypeLayout.setVisibility(View.VISIBLE);
        //                mStateTypeLayout.showLoading();
        //            }
        //
        //            @Override
        //            protected List<HomeTopic> doInBackground(Void... params) {
        //                try {
        //                    Thread.sleep(1000L);
        //                    for (int j = 0; j < 20; j++) {
        //                        HomeTopic homeTopic1 = new HomeTopic();
        //                        homeTopic1.setType(1);
        //                        homeTopic1.setName("优选澳大利亚晚熟脐橙");
        //                        homeTopic1.setDes("来自南半球的甜蜜滋味");
        //                        homeTopic1.setOriginPrice("128");
        //                        homeTopic1.setAccountPrice("88");
        //                        homeTopic1.setImg("http://imgws4.fruitday.com/images/2016-10-21/ac3ee85a95886a29dd0657c17f822f45.png");
        //                        mList.add(homeTopic1);
        //
        //                        HomeTopic homeTopic2 = new HomeTopic();
        //                        homeTopic2.setType(1);
        //                        homeTopic2.setName("佳沛新西兰阳光金果(优选)");
        //                        homeTopic2.setDes("衣服要穿S 金果要吃优选");
        //                        homeTopic2.setOriginPrice("80");
        //                        homeTopic2.setAccountPrice("59.9");
        //                        homeTopic2.setImg("http://imgws4.fruitday.com/images/2016-10-17/dca8f1bb38e46fcc2766acfb460eadde.png");
        //                        mList.add(homeTopic2);
        //
        //                        HomeTopic homeTopic3 = new HomeTopic();
        //                        homeTopic3.setType(1);
        //                        homeTopic3.setName("智利蓝莓");
        //                        homeTopic3.setDes("远离近视 保护心灵窗口");
        //                        homeTopic3.setOriginPrice("90.8");
        //                        homeTopic3.setAccountPrice("88");
        //                        homeTopic3.setImg("http://imgws4.fruitday.com/images/2016-10-17/671781f2a4808b5bd99a77a8fb263547.png");
        //                        mList.add(homeTopic3);
        //
        //                        HomeTopic homeTopic4 = new HomeTopic();
        //                        homeTopic4.setType(1);
        //                        homeTopic4.setName("美国华盛顿甜脆红地厘蛇果");
        //                        homeTopic4.setDes("一口甜脆 营养第四餐");
        //                        homeTopic4.setOriginPrice("60.7");
        //                        homeTopic4.setAccountPrice("49.9");
        //                        homeTopic4.setImg("http://imgws4.fruitday.com/images/2016-10-20/5456079c95e74491f37da4009bd2a9a9.png");
        //                        mList.add(homeTopic4);
        //
        //                        HomeTopic homeTopic5 = new HomeTopic();
        //                        homeTopic5.setType(1);
        //                        homeTopic5.setName("新疆库尔勒香梨");
        //                        homeTopic5.setDes("特别的爱 给特别的梨");
        //                        homeTopic5.setOriginPrice("50.7");
        //                        homeTopic5.setAccountPrice("39.9");
        //                        homeTopic5.setImg("http://imgws4.fruitday.com/images/2016-09-12/9710c9e0204f489140c4f5cbd4f62049.png");
        //                        mList.add(homeTopic5);
        //                    }
        //
        //                } catch (Exception e) {
        //
        //                }
        //
        //                return mList;
        //            }
        //
        //            @Override
        //            protected void onPostExecute(List<HomeTopic> strings) {
        //                super.onPostExecute(strings);
        //                mSearchAdapter.notifyDataSetChanged();
        //                mSvSearch.setVisibility(View.GONE);
        //                mStateTypeLayout.showContent();
        //                mRlAddToCart.setVisibility(View.VISIBLE);
        //            }
        //        });
    }

    /**
     * 初始化搜索历史Recycler View
     */
    private void initSearchHistoryRcv() {
        mSearchHistoryAdapter = new SearchHistoryAdapter(historyList);
        mHistoryRcv.setLayoutManager(new FullyLinearLayoutManager(mActivity));
        mHistoryRcv.setNestedScrollingEnabled(false);
        mHistoryRcv.setSwipeMenuCreator((swipeLeftMenu, swipeRightMenu, viewType) -> {
            SwipeMenuItem deleteItem = new SwipeMenuItem(mActivity)
                    .setBackgroundColor(getResources().getColor(R.color.color_fb6d6c))
                    .setText(R.string.delete)
                    .setTextSize(12)
                    .setWidth(getResources().getDimensionPixelSize(R.dimen.size50));
            swipeRightMenu.addMenuItem(deleteItem);
        });
        mHistoryRcv.setSwipeMenuItemClickListener((closeable, adapterPosition, menuPosition, direction) -> {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                historyList.remove(adapterPosition);
                Utils.saveSearchHistory(historyList);
                mSearchHistoryAdapter.notifyDataSetChanged();
                if (CheckUtils.isEmpty(historyList)) {
                    mLlSearchHistory.setVisibility(View.GONE);
                }
            }

        });
        mHistoryRcv.setAdapter(mSearchHistoryAdapter);
        mSearchHistoryAdapter.setOnHistoryItemClickListener(content -> search(content));
    }

    /**
     * 初始化搜索历史
     */
    private void initSearchHistory() {
        List<String> hisList = Utils.getSearchHistory();
        historyList.clear();
        if (!CheckUtils.isEmpty(hisList)) {
            mLlSearchHistory.setVisibility(View.VISIBLE);
            historyList.addAll(hisList);
            mSearchHistoryAdapter.notifyDataSetChanged();
        } else {
            mLlSearchHistory.setVisibility(View.GONE);
        }
    }

    @Override
    public void btnClearClick() {
        super.btnClearClick();
        mSvSearch.setVisibility(View.VISIBLE);
        mStateTypeLayout.setVisibility(View.GONE);
        mRlAddToCart.setVisibility(View.GONE);
    }

    /**
     * 保存搜索记录 不重复 历史记录存在 移动首位 最多保存10条
     *
     * @param query
     */
    private void saveSearchHistory(String query) {
        List<String> list = Utils.getSearchHistory();
        if (CheckUtils.isEmpty(list)) {
            list = new ArrayList<>();
            list.add(query);
        } else {
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                String item = iterator.next();
                if (CheckUtils.equalsString(query, item)) {
                    iterator.remove();
                }
            }
            list.add(0, query);
        }
        int size = list.size();
        if (size > 10) { // 最多保存10条
            for (int i = size - 1; i >= 10; i--) {
                list.remove(i);
            }
        }
        Utils.saveSearchHistory(list);
        initSearchHistory();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_search;
    }


    @OnClick({R.id.iv_clear_history, R.id.iv_add_to_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clear_history:
                mLlSearchHistory.setVisibility(View.GONE);
                Utils.clearSearchHistory();
                mSvSearch.setVisibility(View.VISIBLE);
                mStateTypeLayout.setVisibility(View.GONE);
                mRlAddToCart.setVisibility(View.GONE);
                break;
            case R.id.iv_add_to_cart:
                Utils.startActivity(mActivity, ShoppingCartActivity.class);
                break;
        }
    }


    @Override
    public void btnRightTextClick() {
        super.btnRightTextClick();
        mActivity.onBackPressedSupport();

    }

    @Override
    public void onAddToCartClick(GoodsInfo item, ImageView imageView) {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
            addToCart(item, imageView);
        } else {
            LogicCodeBlock.create().registerLogicCodeCallback(logicState -> {
                if (logicState == LogicCodeBlock.LogicState.AddToCart.value)
                    addToCart(item, imageView);
            });
        }
    }


    /**
     * 显示规格选弹框
     *
     * @param goodsInfo
     * @param imageView
     */
    private void showSpecPop(GoodsInfo goodsInfo, ImageView imageView) {
        if (Utils.isShowSpePop(goodsInfo.getGoodsType(), goodsInfo.getGoodsSkuId())) {

            Utils.showSpecPop(mActivity, getView(), 1, goodsInfo.getGoodsPic(), goodsInfo.getGoodsSkuId(), goodsInfo.getSelectedSkuId(), goodsInfo.getSku(), goodsInfo.getSkuMap(), new GoodsSpecPopUtils.OnPopClickListener() {
                @Override
                public void onAddToCart(View v, int goodsSkuId) {
                    // 设置gooSkuId
                    goodsInfo.setGoodsSkuId(goodsSkuId);
                    addToCart(goodsInfo, imageView);
                    //重置goodsSkuId
                    goodsInfo.setGoodsSkuId(0);
                }

                @Override
                public void onSpecSelect(SkuEntity skuEntity) {
                    goodsInfo.setSelectedSkuId(skuEntity.getGoodsSkuId());
                }
            });

        } else {// 不是sku商品，或是sku商品但是后台根据sku的类型分类成多个商品返回出来
            addToCart(goodsInfo, imageView);
        }

    }

    /**
     * 加入购物车
     *
     * @param item
     * @param imageView
     */
    private void addToCart(GoodsInfo item, ImageView imageView) {
        ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), item.getGoodsId(), Utils.getSupplierId(), item.getShopId(), item.getGoodsSkuId(), 1, 0, new DialogCallback<GoodsStock>(mActivity/*, getString(R.string.adding)*/) {
            @Override
            public void onSuccess(GoodsStock o, Call call, Response response) {
                //                    if (o.getStockNumber() == 0) {
                //                        XTipsDialog.showFail(mActivity, getString(R.string.not_enough));
                //                    } else {
                ShopAnimationUtils.addToShoppingCart(mActivity, 0, imageView, mIvAddToCart, mRlContent, true, () -> {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                    //                        XTipsDialog.showSuccess(mActivity, getString(R.string.add_suc));
                    ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
                });
                //                    }

            }
        });
    }


    @Override
    public void onDestroyView() {
        if (mEditText != null && contentTextWatcher != null) {
            mEditText.removeTextChangedListener(contentTextWatcher);
            contentTextWatcher = null;
        }

        super.onDestroyView();
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_PAY_FINISH:
                mActivity.finish();
                break;
            case LeEventCode.MSG_CODE_SET_SHOPPINGCART_SUCS://购物车数量改变
                ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
                break;
        }

    }
}
